#!/usr/bin/python
#-*-coding: utf-8 -*-

__all__ = [u'GuiPart']

########## DO NOT CHANGE THESE LINES ###########################################
import sys
from pylot.core import (ENCODING, Path)
try : __file__
except NameError : co = sys._getframe(0).f_code ; __file__ = co.co_filename
ufile = __file__.decode(ENCODING)
if ufile.strip() : PLUGIN_PATH = Path(ufile).abspath().parent
else : PLUGIN_PATH = Path(u'.').abspath()
########## DO NOT CHANGE THESE LINES ###########################################

from PyQt4 import QtGui
from PyQt4.QtCore import SIGNAL
from handler import HandlerPart
from pylot.qtgui import (load_designer_file, GuiAutoWidget, GuiPathChooser,
                            GuiUnicodeChooser, GuiCollectionEditor)
from pylot.core import (Configuration, ConfigOptionBook)


#_GuiPartPrefs, WidgetClass = load_designer_file(u'prefs.ui', [PLUGIN_PATH])
#class GuiPartPrefs(WidgetClass, GuiAutoWidget, _GuiPartPrefs):
#  def __init__(self, handler, options):
#    GuiAutoWidget.__init__(self, handler)
#    self._plugin_path = PLUGIN_PATH
#    WidgetClass.__init__(self)
#    self.setupUi(self) # Designer file initialization
#
#    self.opt = options
#    self.builds_path_chooser = GuiPathChooser(self.opt[u'pathbook'][u'builds'])
#    self.layout_paths.addWidget(self.builds_path_chooser)
#    self.build_suffix_chooser = GuiUnicodeChooser(self.opt[u'general'][u'build_suffix'])
#    self.layout_build_options.addWidget(self.build_suffix_chooser)

_GuiPart, WidgetClass = load_designer_file(u'designer.ui', [PLUGIN_PATH])
class GuiPart(WidgetClass, GuiAutoWidget, _GuiPart):
  u"""
  A tool to launch CMake, Make, ...
  """
  def __init__(self, handler=None):
    if handler is None :
      handler = HandlerPart()
      handler.init()
    GuiAutoWidget.__init__(self, handler)
    self._plugin_path = PLUGIN_PATH

    WidgetClass.__init__(self)
    self.setupUi(self) # Designer file initialization

    # Widget creation
    self._createActions()
    self._createPreferences()
    self._createConnexions()
    self._createMenus()
    self._createToolBars()

    self.options = GuiCollectionEditor(self.handler.options_book,
      groupbook=self.handler.groupbook, handler=self.handler)
    self.options_expert = GuiCollectionEditor(self.handler.options_book_expert,
      groupbook=self.handler.groupbook, handler=self.handler)

    self.addpyLotWidget(self.options)
    self.addpyLotWidget(self.options_expert)
  # ============================================================================
  # Widget Creation
  # ============================================================================

  def _createActions(self):
    u"""
    See 'designer.ui' file (Qt Designer file) to know defined actions
    """
    pass

  def _createConnexions(self):
    self.connect(self.action_set_src, SIGNAL("triggered()"), self.setSrcDir)

    self.connect(self.action_make, SIGNAL("triggered()"), self.make)
    self.connect(self.action_make_install, SIGNAL("triggered()"), self.makeInstall)
    self.connect(self.action_make_install_debu_G, SIGNAL("triggered()"), self.makeInstallDebug)
    self.connect(self.action_erase_and_make_install, SIGNAL("triggered()"), self.eraseAndMakeInstall)
    self.connect(self.action_erase_and_make_install_debu_G, SIGNAL("triggered()"), self.eraseAndMakeInstallDebug)
    self.connect(self.action_make_doc, SIGNAL("triggered()"), self.makeDoc)
    self.connect(self.action_save_options, SIGNAL("triggered()"), self.saveOptions)
    self.connect(self.action_save_as_options, SIGNAL("triggered()"), self.saveOptionsAs)
    self.connect(self.action_load_options, SIGNAL("triggered()"), self.loadOptions)
    self.connect(self.action_reload_options, SIGNAL("triggered()"), self.reloadOptions)
    self.connect(self.action_set_options_to_default, SIGNAL("triggered()"), self.defaultOptions)

    self.connect(self.action_clean_cache, SIGNAL("toggled(bool)"),
                 self._onActionCleanCacheTriggered)
    self.connect(self.action_debug_mode, SIGNAL("toggled(bool)"),
                 self._onActionDebugModeTriggered)

  def _createPreferences(self):
    config = Configuration()
    config.identity = self.handler.opt.identity

    book = ConfigOptionBook()
    book.identity = self.handler.opt[u'general'].identity
    book.add(self.handler.opt[u'general'][u'build_suffix'])
    config.addBook(book)

    book = ConfigOptionBook()
    book.identity = self.handler.opt[u'pathbook'].identity
    book.add(self.handler.opt[u'pathbook'][u'builds'])
    config.addBook(book)
    self.pref = GuiCollectionEditor(config, handler=self.handler)

  def _createMenus(self):
    self.menu_file = QtGui.QMenu()
    self.menu_file.setObjectName(u"menu_file")
    self.addMenu_(self.menu_file)

    self.menu_edit = QtGui.QMenu()
    self.menu_edit.setObjectName(u"menu_edit")
    self.addMenu_(self.menu_edit)

    self.menu_build = QtGui.QMenu()
    self.menu_build.setObjectName(u"menu_build")
    self.addMenu_(self.menu_build)

    self.menu_make = QtGui.QMenu()
    self.menu_make.setObjectName(u"menu_make")

    self.menu_erase_and_make = QtGui.QMenu()
    self.menu_erase_and_make.setObjectName(u"menu_erase_and_make")

    self.menu_options = QtGui.QMenu()
    self.menu_options.setObjectName(u"menu_options")

  def _createToolBars(self):
    #tool_bar_make
    self.tool_bar_make = QtGui.QToolBar()
    self.tool_bar_make.setObjectName(u'tool_bar_make')
    self.addToolBar_(self.tool_bar_make)

  def getDockableWidgets(self):
    return [
      (self.options, u'user'),
      (self.options_expert, u'expert')
      ]

  # ============================================================================
  # Widget dynamic changes
  # ============================================================================

  def _switchUserLevel(self, level):
    pass

  def _translate(self):
    self._setTexts([
      (self.menu_build, self.tr_(u"&Build")),
      (self.menu_make, self.tr_(u"&Make")),
      (self.menu_erase_and_make, self.tr_(u"&Erase and Make")),
      (self.menu_options, self.tr_(u"CMake Options")),

      (self.tool_bar_make, self.tr_(u"Build ToolBar"))
      ])

  def _updateData(self):
    pass

  def _refresh(self):
    self.action_clean_cache.setChecked(self.handler.cleancache)
    self.action_debug_mode.setChecked(self.handler.debug_mode)

  def _decorate (self):
    self._setIcons([
      (self.menu_erase_and_make, u'buildErase.png'),
      (self.menu_make, u'buildMake.png'),
      (self.menu_options, u'cmake.png'),

      (self.action_clear_output_and_make_install, u'buildEraseAndMakeInstall.png'),
      (self.action_erase, u'buildErase.png'),
      (self.action_erase_all, u'buildEraseAll.png'),
      (self.action_erase_and_make_install, u'buildEraseAndMakeInstall.png'),
      (self.action_erase_and_make_install_debu_G, u'buildEraseAndMakeInstallDebug.png'),
      (self.action_make, u'buildMake.png'),
      (self.action_make_doc, u'buildMakeDoc.png'),
      (self.action_make_install, u'buildMakeInstall.png'),
      (self.action_make_install_debu_G, u'buildMakeInstallDebug.png'),

      (self.action_load_options, u'optionsOpen.png'),
      (self.action_reload_options, u'optionsRefresh.png'),
      (self.action_save_as_options, u'optionsSaveAs.png'),
      (self.action_save_options, u'optionsSave.png'),
      ])

  def _fillToolBars(self, level):
    self._fill(self.tool_bar_make, [
      self.action_make_install,
      (self.action_make_install_debu_G, u'devel'),
      ])

  def _fillMenus(self, level):
    self._fill(self.menu_file,
      [
      self.action_set_src,
      ])

    self._fill(self.menu_edit,
      [
      self.menu_options
      ])

    self._fill(self.menu_make,
      [
      self.action_make,
      self.action_make_doc,
      self.action_make_install,
      (self.action_make_install_debu_G, u'devel'),
      ])

    self._fill(self.menu_erase_and_make,
      [
      self.action_erase_and_make_install,
      (self.action_erase_and_make_install_debu_G, u'devel'),
      ])

    self._fill(self.menu_build,
      [
      self.menu_make,
      self.menu_erase_and_make,
      (u'-', u'devel'),
      (self.action_clean_cache, u'devel')
      ])

    self._fill(self.menu_options,
      [
      self.action_save_options,
      self.action_save_as_options,
      self.action_load_options,
      self.action_reload_options,
      self.action_set_options_to_default,
      ])

  def _readSettings(self, settings, common):
    pass

  def _writeSettings(self, settings, common):
    pass

  def _quit(self):
    pass

  # ============================================================================
  # Widget/HandlerPart Connections
  # ============================================================================

  def _eraseAndMake (self, target, debug):
    txt = self._buildName(target, debug)
    build_dir = self.handler.eraseAndBuild(target=u'install', debug=debug,
      force=False)
    rep = QtGui.QMessageBox.critical (self, self.tr_(u"Erase directory"),
      self.tr_(u"Are you sure you want to erase ALL files in directory %s ?") % build_dir,
      QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel)

    if rep == QtGui.QMessageBox.Ok :
      self.handler.eraseAndBuild(target=u'install', debug=debug, force=True,
        make=True)

  def _buildName (self, target, debug):
    u"""
    generate buuld name. Exemple : 'install "Standard" version',
    'test "debug" version'
    :param target: make target
    :type target: str
    :param debug: debug mode ?
    :type debug: bool
    :return: build name
    :rtype: str
    """
    if debug is True :
      version = self.tr_(u'"Debug" version')
    else :
      version = self.tr_(u'"Standard" version')
    text = u'%s %s' % (target, version)
    return text

  def _make (self, target, debug):
    self.handler.build (target=target, debug=debug,
      cleancache=self.handler.cleancache)

  # ============================================================================
  # Widget Public Methods
  # ============================================================================
  # define here all methods you want to be reachable outside this widget
  # these methods are useful to embed this plugin in an other

  def eraseAndMakeInstall(self):
    self._eraseAndMake(u'install', False)

  def eraseAndMakeInstallDebug(self):
    self._eraseAndMake(u'install', True)

  def make(self):
    self._make(u'', False)

  def makeInstall(self):
    self._make(u'install', False)

  def makeInstallDebug(self):
    self._make(u'install', True)
  
  def makeDoc(self):
    self._make(u'doxygen',False)

  def defaultOptions(self):
    self.options.resetDataToDefault()
    self.options_expert.resetDataToDefault()

  def reloadOptions(self):
    self.handler.loadCMakeOptions()
    self.handler.splitCMakeOptions(self.handler.cmake_options)
    self.options.refresh()
    self.options_expert.refresh()

  def loadOptions(self) :
    configfile = QtGui.QFileDialog().getOpenFileName(self,
      self.tr_(u"load CMake options"), self.handler.pathbook(u'cmakeoptions'))
    if configfile :
      self.handler.loadCMakeOptions(unicode(configfile))
      self.handler.splitCMakeOptions(self.handler.cmake_options)
      self.options.refresh()
      self.options_expert.refresh()
      self.handler.pathbook[u'cmakeoptions'] = Path(unicode(configfile)).parent

  def saveOptions(self):
    u"""
    Which options_book to save
    """
    self.handler.saveCMakeOptions()

  def saveOptionsAs(self):
    configfile = QtGui.QFileDialog().getSaveFileName(self,
      self.tr_(u"save config"), self.handler.pathbook(u'cmakeoptions'))

    if configfile :
      self.manager.saveCMakeOptions(unicode(configfile))
      self.handler.pathbook[u'cmakeoptions'] = Path(unicode(configfile)).parent

  def setSrcDir(self):
    src = unicode(QtGui.QFileDialog().getExistingDirectory(self,
      self.tr_(u"Choose source directory")))
    if src :
      self.handler.pathbook[u'src'].value = src
      self.handler.updateCMakeOptions()
      self.reloadOptions()

  def _onActionCleanCacheTriggered(self, value):
    self.handler.cleancache = bool(value)

  def _onActionDebugModeTriggered(self, value):
    self.handler.debug_mode = bool(value)

if __name__ == u"__main__":
  from PyQt4.QtGui import QApplication
  app = QApplication([])
  gui = GuiPart()
  gui.show()
  ret = app.exec_()
